// 实现对User表的增删改查
const { User } = require('../model/create_tables')
const { Sequelize, Op } = require('sequelize')

/* 新增用户 */
const addUser = async (userObj) => {
  try {
    const res = await User.create(userObj)
    return {
      message: '新增用户成功',
      data: res.toJSON(),
      status: 1,
    }
  } catch (error) {
    if (error instanceof Sequelize.UniqueConstraintError) {
      throw new Error('USERNAME_EXISTS') // 自定义错误标识
    }
    // 其他错误直接抛出
    throw error
  }
}

/* 查询用户 */
// 根据id查询用户
const getUserById = async (id) => {
  const res = await User.findByPk(id)
  if (res) {
    return {
      message: '查询成功',
      data: res.toJSON(),
      status: 1,
    }
  } else {
    return {
      message: '未找到该用户',
      status: 0,
    }
  }
}

// 根据用户名查询用户
const getUserByName = async (name) => {
  let where = {}
  if (name && name.trim() !== '') {
    where.username = name
  }
  const res = await User.findAll({ where })
  const data = res.map((user) => user.toJSON())
  if (data.length === 0) {
    return { status: 0, message: '未找到用户' }
  } else {
    return {
      status: 1,
      message: `找到${data.length}个用户`,
      data: data,
    }
  }
}

// 根据用户名及密码查询用户,有则登录成功，无则登录失败
const loginUser = async (username, password) => {
  const res = await User.findAll({
    where: {
      username: username,
      password: password,
    },
  })
  if (res.length >= 2) {
    return {
      message: '找到多个用户',
      data: res.map((user) => user.toJSON()),
      status: 1,
    }
  } else if (res.length == 1) {
    return {
      message: '找到一个用户',
      data: res[0].toJSON(),
      status: 1,
    }
  } else {
    return {
      message: '未找到该用户',
      status: 0,
    }
  }
}

/* 软删除用户 */
const deleteUser = async (id) => {
  const res = await User.destroy({
    where: {
      id,
    },
  })
  if (res === 1) {
    return {
      message: '删除成功',
      status: 1,
    }
  } else {
    return {
      message: '删除失败',
      status: 0,
    }
  }
}

/* 更新用户信息 */
const updateUser = async (id, userObj) => {
  try {
    // 先根据id查询用户
    const user = await User.findByPk(id)
    if (!user) {
      return {
        message: '未找到该用户，修改失败',
        status: 0,
      }
    }
    const res = await User.update(userObj, {
      where: {
        id,
      },
    })
    if (res[0] === 1) {
      return {
        message: '修改成功',
        status: 1,
      }
    } else {
      return {
        message: '未修改任何信息',
        status: 1,
      }
    }
  } catch (error) {
    if (error instanceof Sequelize.UniqueConstraintError) {
      throw new Error('USERNAME_EXISTS') // 抛出与addUser一致的自定义错误
    }
    throw error // 其他错误直接抛出
  }
}

exports.addUser = addUser
exports.getUserById = getUserById
exports.getUserByName = getUserByName
exports.loginUser = loginUser
exports.deleteUser = deleteUser
exports.updateUser = updateUser
